package com.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.blog.constants.SystemConstants;
import com.blog.domain.entity.LoginUser;
import com.blog.domain.entity.User;
import com.blog.mapper.MenuMapper;
import com.blog.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private MenuMapper menuMapper;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		//根据用户名查询用户信息
		LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
		lambdaQueryWrapper.eq(User::getUserName,username);
		User user = userMapper.selectOne(lambdaQueryWrapper);
		//判断是否查到用户，未查到抛出异常
		if (Objects.isNull(user)){
			throw new RuntimeException("用户不存在");
		}
		//查到用户，返回用户信息,后台用户才需要进行权限控制，前台不需要
		if(user.getType().equals(SystemConstants.ADMAIN)){
			//是后台用户
			//权限集合
			List<String> list = menuMapper.selectPermByUserId(user.getId());
			return new LoginUser(user,list);
		}

		return new LoginUser(user,null);
	}
}
